<template>
  <div class="stage">
    <div class="canvas">
      <div class="welcome">
        <img class="logo" src="@/assets/login/login_logo.png" alt="" />
        欢迎登录运营管理平台
      </div>

      <img class="illust" src="@/assets/login/login_ct.png" alt="" />

      <div class="card">
        <img class="card-top-img" src="@/assets/login/card-top-img.png" alt="" />
        <!-- 登录表单（内部自带 密码/短信 tab + 图形码 + 发送短信） -->
        <LoginForm ref="loginRef" :loading="submitting" @submit="handleSubmit" @forget="openForgot" />
      </div>
    </div>
  </div>

  <!-- 忘记密码：通用弹窗组件（仅负责“忘记密码”场景；强制改密放到 layout） -->
  <PasswordResetDialog v-model="showForgot" scene="forgot" :mobile="forgotMobile" @success="onForgotSuccess" />

  <!-- ✅ 抽成组件：多品牌选择（仅当返回多个候选时展示） -->
  <BrandSelectorDialog
    v-model="showBrandDialog"
    :list="brandList"
    v-model:selected-id="selectedBrandId"
    title="选择品牌"
    width="404px"
    @cancel="handleCancelBrand"
    @confirm="handleConfirmBrand"
  />
</template>

<script setup>
  import LoginForm from "./components/LoginForm.vue";
  import PasswordResetDialog from "./components/PasswordResetDialog.vue";
  import BrandSelectorDialog from "./components/BrandSelectorDialog.vue";

  import Local from "tools-utils/storage";
  import { initBackEndControlRoutes } from "@/router/backEndRoute";
  import { useUserInfoStore } from "@/store/modules/userInfo";
  import { NextLoading } from "@/utils/loading";

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserInfoStore();

  const submitting = ref(false);
  const loginRef = ref(null);

  /* ========== 忘记密码（仅忘记密码场景；强制改密移到 layout 里） ========== */
  const showForgot = ref(false);
  const forgotMobile = ref("");
  function openForgot(mobileFromForm) {
    // LoginForm 通过 defineExpose 暴露 form，可兜底取输入手机号
    // forgotMobile.value = mobileFromForm || loginRef.value?.form?.mobile || "";
    forgotMobile.value = "";
    showForgot.value = true;
  }
  function onForgotSuccess({ mobile }) {
    if (mobile) loginRef.value.form.mobile = mobile;
    loginRef.value?.refreshCaptcha?.();
  }

  /* ========== 候选客户/品牌选择 ========== */
  const brandList = ref([]); // 登录第一步返回的候选
  const showBrandDialog = ref(false);
  const selectedBrandId = ref(""); // 选中的 customer.id（字符串）

  watch(showBrandDialog, v => {
    if (v && brandList.value.length) {
      const first = brandList.value[0];
      selectedBrandId.value = String(first?.customer?.id || first?.id || "");
    }
  });
  function handleCancelBrand() {
    showBrandDialog.value = false;
  }

  /* ========== 登录提交：密码/短信模式共用 ========== */
  async function handleSubmit(payload) {
    try {
      submitting.value = true;

      const candidates =
        payload.mode === "pwd" ? await userStore.LoginByPwd(payload) : await userStore.LoginByCode(payload);

      const list = Array.isArray(candidates) ? candidates : [];
      if (list.length === 0) {
        $msg.warning("很抱歉，你的账号暂时不能登录，可能已停用或已过期，如有疑问请联系客服。");
        return;
      }

      if (list.length === 1) {
        // 只有一个客户：不弹窗，直接选择
        await chooseAndGo(list[0]);
        return;
      }

      // 多个客户：弹出选择弹窗
      brandList.value = list;
      showBrandDialog.value = true;
    } catch (e) {
      console.error("[Login] handleSubmit error:", e);
      loginRef.value?.refreshCaptcha?.();
    } finally {
      submitting.value = false;
    }
  }

  /** 弹窗点击确认：直接把 BrandSelectorDialog 回传的原始对象丢给二次登录 */
  async function handleConfirmBrand(raw) {
    if (!raw) {
      $msg.warning("请选择一个品牌");
      return;
    }
    await chooseAndGo(raw);
  }

  /** 第二步：选择客户 -> token 与用户信息进入 store（强制改密交给 layout） */
  async function chooseAndGo(candidate) {
    const id = candidate?.customer?.id ?? candidate?.id;
    const sign = candidate?.sign;
    const tenantId = candidate?.customer?.tenantId;

    if (!id) {
      $msg.error("品牌信息异常");
      return;
    }

    await userStore.ChooseUser({ id, sign, tenantId });
    showBrandDialog.value = false;
    await afterLoginRedirect();
  }

  /** 登录成功后的跳转（动态路由 + redirect） */
  async function afterLoginRedirect() {
    const isNoPower = await initBackEndControlRoutes();
    if (isNoPower) {
      $msg.warning("抱歉，您没有登录权限");
      Local.clear();
      return;
    }

    if (route.query?.redirect) {
      router.push({
        path: route.query.redirect,
        query: Object.keys(route.query?.params || {}).length ? JSON.parse(route.query.params) : "",
      });
    } else {
      router.push("/");
    }
    NextLoading.start();
  }
</script>

<style lang="scss" scoped>
  img,
  svg {
    -webkit-user-drag: none;
    user-select: none;
  }

  .stage {
    min-width: 1440px;
    min-height: 900px;
    overflow: auto !important;
    width: 100vw;
    height: 100%;
    display: grid;
    place-items: center;
    background-image: url("@/assets/login/login_bg.jpg");
    background-size: 100% 100%;
    background-position: center;
    background-repeat: no-repeat;
    font-family: "PingFang SC", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
  }
  .canvas {
    position: relative;
    aspect-ratio: 16 / 10;
    width: max(1440px, min(100vw, 160vh));
    height: max(900px, calc((min(100vw, 160vh)) / 16 * 10));
  }
  .welcome {
    position: absolute;
    left: 8.333%;
    top: 6.222%;
    height: 7.111%;
    color: var(--ct1);
    font-weight: 600;
    font-size: clamp(32px, 2.22vw, 40px);
    display: inline-flex;
    align-items: center;
    gap: 4px;
    user-select: none;
    .logo {
      width: calc(72 / 460 * 100%);
      height: auto;
      aspect-ratio: 1;
      object-fit: contain;
    }
  }
  .illust {
    position: absolute;
    left: 6.25%;
    top: 23%;
    width: 44.444%;
    height: auto;
  }

  .card {
    position: absolute;
    right: 11.11%;
    top: 27%;
    width: 400px;
    height: 453px;
    border-radius: 20px;
    background: rgba(255, 255, 255, 0.7);
    box-shadow: 0 0 24px 0 #0000000d;
    border: 1px solid #ffffff;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .card-top-img {
      position: absolute;
      left: 0;
      top: 0;
      z-index: 0;
      width: 100%;
      height: 16.78%;
      object-fit: cover;
    }
  }
</style>
